import store from "@/store"
import cartApi from "@/api/cartApi"
import userUtils from "@/utils/userUtils"

const cartUtils = {
    // 获取购物车列表
    getCartList() {
        return store.state.cartModule.cartList;
    },
    // 获取选中的购物车列表
    getSelectedCartList() {
        var list = [];
        this.getCartList().forEach(cart => {
            if (cart.selected) {
                list.push(cart)
            }
        })
        return list;
    },
    // 选择购物车
    selectCart(id, selected) {
        store.commit("cartModule/selectCart", { id: id, selected: selected });
    },
    // 全部选中或取消
    selectAllCart(selected) {
        store.commit("cartModule/selectAllCart", selected);
    },
    isAllSelected() {
        return store.getters['cartModule/isAllSelected'];
    },
    // 设置购物车列表
    async refreshCartList() {
        var res = await cartApi.cart.list(userUtils.getUserId());
        var prevCartList = store.state.cartModule.cartList;
        var currentCartList = res.data;
        currentCartList.forEach(currentCart => {
            currentCart.selected = false;
            prevCartList.forEach(prevCart => {
                if (currentCart.skuId == prevCart.skuId) {
                    currentCart.selected = prevCart.selected;
                }
            })
            if(!currentCart.stockEnough) {
                currentCart.selected = false;
            }
        })
        store.commit("cartModule/setCartList", currentCartList);
    },
}

export default cartUtils;